package com.slofzx.nuoda.sso.service.impl;

import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.slofzx.nuoda.common.enums.CommonResultEnum;
import com.slofzx.nuoda.common.enums.LoginTypeEnum;
import com.slofzx.nuoda.common.exception.ServiceException;
import com.slofzx.nuoda.common.feign.UserClient;
import com.slofzx.nuoda.common.service.SysUserService;
import com.slofzx.nuoda.common.util.JWTUtil;
import com.slofzx.nuoda.common.vo.SysUserVO;
import com.slofzx.nuoda.sso.dto.SsoAppInfoDTO;
import com.slofzx.nuoda.sso.dto.SsoLoginDTO;
import com.slofzx.nuoda.sso.enums.SsoLoginResultEnum;
import com.slofzx.nuoda.sso.service.SsoAppInfoService;
import com.slofzx.nuoda.sso.service.SsoLoginService;
import com.slofzx.nuoda.sso.vo.SsoAppInfoVO;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
public class SsoLoginServiceImpl implements SsoLoginService {
    @Autowired
    private SysUserService userService;
    @Autowired
    private SsoAppInfoService ssoAppInfoService;

    private Logger logger = LoggerFactory.getLogger(this.getClass());
    @Override
    public String getToken(SsoLoginDTO dto) {

        if(dto == null) {
            throw new ServiceException(SsoLoginResultEnum.APP_LICENCE_ERROR,"app licence错误",dto);
        }
        if(dto.getLoginId() == null) {
            throw new ServiceException(SsoLoginResultEnum.APP_USER_NOT_FOUND,"app 获取token，无用户信息",dto);
        }
        SsoAppInfoVO appInfoVO = ssoAppInfoService.queryById(dto.getAppId());

        if(appInfoVO == null) {
            throw new ServiceException(SsoLoginResultEnum.APP_NOT_FOUND,"未找到对应的app",dto);
        }
        if(appInfoVO.isDisabled()) {
            throw new ServiceException(SsoLoginResultEnum.APP_DISABLED,"app未启用",dto);
        }
        if(appInfoVO.getSecret().equals(dto.getSecret()) == false) {
            throw new ServiceException(SsoLoginResultEnum.APP_LICENCE_ERROR,"app licence错误",dto);
        }
        if(StringUtils.isNotEmpty(appInfoVO.getAllowIps())){
            if((","+appInfoVO.getAllowIps()+",").contains(","+dto.getClientIp()+",") == false){
                throw new ServiceException(SsoLoginResultEnum.APP_IP_DENY,"app 获取token不在白名单内",dto);
            }
        }

        SysUserVO userVO = userService.getUserByLoginName(dto.getLoginId());
        if(userVO == null) {
            throw new ServiceException(SsoLoginResultEnum.APP_USER_NOT_FOUND,"app 获取token，无用户信息",dto);
        }

        Date now = new Date();
        Map<String, String> playloadData = new HashMap();
        playloadData.put("username", userVO.getLoginName());
        playloadData.put("loginType", LoginTypeEnum.THIRD_PARTY.getId());
        long tokenExpireTime = now.getTime() + 24*60*60*1000;
        String token = JWTUtil.createToken(playloadData, new Date(tokenExpireTime));
        return token;
    }

    @Override
    public boolean checkToken(SsoLoginDTO dto) {
        try {
            String token = dto.getToken();
            DecodedJWT decodedJWT = JWTUtil.decodeToken(token);
            String username = decodedJWT.getClaim("username").asString();
            String loginType = decodedJWT.getClaim("loginType").asString();
            Date expireTime = decodedJWT.getExpiresAt();
            if (expireTime.getTime() - (new Date()).getTime() > 0L) {
                return true;
            }
        } catch (TokenExpiredException e) {
            this.logger.error("jwt信息已过期:{}", e, dto);
        } catch (Exception e) {
            this.logger.error("解析jwt信息异常:{}", e, dto);
        }
        return false;
    }
}
